package com.bawei.play

import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.LinearLayout
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.aspect.annotation.CheckLogin
import com.bawei.common.entity.CommendEntity
import com.bawei.common.entity.ReplyCommendEntity
import com.bawei.common.entity.VideoEntity
import com.bawei.common.mvi.BaseMviActivity
import com.bawei.play.adapter.CommendExpandListAdapter
import com.bawei.play.adapter.VideoCommendAdapter
import com.bawei.play.adapter.VideoPlayAdapter
import com.bawei.play.commend.CommendDialogFragment
import com.bawei.play.databinding.ActivityVideoPlayBinding
import com.bawei.play.viewmodel.VideoPlayViewModel
import com.bumptech.glide.Glide
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

/**
 * 视频播放页面
 */
@AndroidEntryPoint
@Route(path = "/video/play")
class VideoPlayActivity : BaseMviActivity<ActivityVideoPlayBinding>() {

    //ARouter在Kotlin中注入参数时，使用@JvmFiled注解需要注入变量，也可以使用lateinit关键字定义延迟初始化变量
    @Autowired
    lateinit var videoEntity: VideoEntity

    @JvmField
    @Autowired
    var typeId: Int = -1
    @JvmField
    @Autowired
    var channelId: String = ""

    private val mViewModel: VideoPlayViewModel by viewModels()
    private lateinit var mRecyclerView: VideoRecyclerView
    private lateinit var mAdapter: VideoPlayAdapter
    private lateinit var layoutManager: SnapPageLayoutManager

    private lateinit var llCommentPanel: LinearLayout
    private lateinit var mRvCommends: RecyclerView
    private lateinit var mRlvCommends: CustomExpandListView
    private lateinit var mCommendAdapter: VideoCommendAdapter
    private lateinit var mExpandListCommendAdapter: CommendExpandListAdapter

    private var mVideoPlayer: StandardGSYVideoPlayer? = null
    private var videoList = mutableListOf<VideoEntity>()
    private var commendList = mutableListOf<CommendEntity>()
    private var locReplayList = mutableListOf<ReplyCommendEntity>()
    private var mCurrentPage = 0

    private var pageIndex = 1
    private var pageSize = 10

    override fun getLayoutId(): Int = R.layout.activity_video_play

    override fun initViews() {
        //依赖注入实体对象
        ARouter.getInstance().inject(this)
        //添加传递过来视频数据，做为第一条数据
        videoEntity?.let { videoList.add(it) }

        //初始化RecyclerView
        mRecyclerView = mDataBinding.rvVideo
        //默认ItemView缓存大小为2, 数值越大缓存的Item就越多，占用内存就越大
        mRecyclerView.setItemViewCacheSize(10)
        mRecyclerView.setHasFixedSize(true) //Item布局大小为固定大小

        //适当调整缓存池大小
        var pool = RecyclerView.RecycledViewPool()
        pool.setMaxRecycledViews(0, 5)
        mRecyclerView.setRecycledViewPool(pool)
        //根据RecyclerView的滚动事件来暂停或恢复加载
        mRecyclerView.addOnScrollListener(object: RecyclerView.OnScrollListener(){
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                /**
                 * 视频预加载技术方案: 提前利用DownloadManger/OkHttp/后台服务下载视频文件到本地磁盘或者SDK卡中
                 * 切换时根据文件名或者文件路径做判断是否下载成功，如果下载成功就从本地文件中加载视频，反之则加载网络URL的视频
                 */
                mCurrentPage = layoutManager.findFirstVisibleItemPosition()
                videoEntity = videoList[mCurrentPage]
                //获取当前位置布局中的GSY播放器
                mVideoPlayer = (mRecyclerView.findViewHolderForLayoutPosition(mCurrentPage) as VideoPlayAdapter.VideoPlayViewHolder).dataBinding.gsyPlayer
                if(mVideoPlayer != null){
                    mVideoPlayer?.isLooping = true
                    mVideoPlayer?.startPlayLogic()
                }
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                //根据滚动状态暂停或恢复图片加载
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Glide.with(this@VideoPlayActivity).resumeRequests() //回复图片加载
                } else {
                    Glide.with(this@VideoPlayActivity).pauseRequests() //暂停图片加载
                }

                //滚动时需要释放播放器
                if(mVideoPlayer != null && newState == RecyclerView.SCROLL_STATE_DRAGGING){
                    mVideoPlayer?.release()
                }
            }
        })
        //取消不需要的Item动画
        (mRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false

        //下来刷新与加载更多
        mDataBinding.smartRefresh.setOnRefreshListener {
            //重置页面索引
            pageIndex = 1
            //重新加载第一页
            loadVideoList()
        }

        layoutManager = SnapPageLayoutManager(this@VideoPlayActivity)
        mRecyclerView.layoutManager = layoutManager
        mAdapter = VideoPlayAdapter(videoList)
        mAdapter.setOnItemClickListener(object : VideoPlayAdapter.OnItemClickListener{
            override fun onItemChildClick(v: View?, position: Int) {
                when(v?.id){
                    R.id.iv_head -> {}
                    R.id.iv_add -> addGuanZhu()
                    R.id.iv_dian_zan_btn -> videoDianZan()
                    R.id.iv_ping_lun_btn -> showCommendList(position)
                    R.id.iv_share_btn -> videoShared()
                    R.id.iv_shou_cang_btn -> videoShouCang()
                    R.id.iv_close -> closeCommendList()
                    R.id.iv_send -> sendCommend()
                }
            }
        })

        mRecyclerView.swapAdapter(mAdapter, true)

        //本地模拟测试评论回复数据
        mockReplyCommentData()
    }

    //模拟评论回复数据
    private fun mockReplyCommentData(){
        locReplayList.add(ReplyCommendEntity(0, 0, "我来了", "2023-12-20 14:23:21", 0, "小西", 0, 1, "" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "假的真不了", "2023-12-20 14:23:23", 1, "爱哭的小孩", 0, 1, "" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "言之有理", "2023-12-20 14:23:25", 2, "东北大娘", 0, 1, "" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "我觉得太假了，一点儿不真实！！", "2023-12-20 14:23:26", 3, "可可西里", 0, 1, "" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "啥也不是！！", "2023-12-20 14:23:26", 4, "小圆圆", 0, 1, "" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "太傻了！！", "2023-12-20 14:23:26", 5, "兔兔", 0, 1, "" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "我觉得太假了，一点儿不真实！！", "2023-12-20 14:23:26", 6, "蕾蕾", 0, 1, "" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "给你点赞！！", "2023-12-20 14:23:26", 7, "星星", 0, 1, "" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "努力加油！！", "2023-12-20 14:23:26", 8, "星辰大海", 0, 1, "" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "我觉得太假了，一点儿不真实！！", "2023-12-20 14:23:26", 9, "小小鸟", 0, 1, "" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "加油！！", "2023-12-20 14:23:26", 10, "二次元", 0, 1, "" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "一点儿不真实！！", "2023-12-20 14:23:26", 11, "嘻嘻妹妹", 0, 1, "" ))
        locReplayList.add(ReplyCommendEntity(0, 0, "牛逼牛逼，太漂亮了！！", "2023-12-20 14:23:26", 12, "宝马", 0, 1, "" ))
    }

    @CheckLogin
    fun videoDianZan(){

        showToastMessage("点赞！！")

    }

    @CheckLogin
    fun videoShared(){

    }

    @CheckLogin
    fun videoShouCang(){

    }

    @CheckLogin
    fun addGuanZhu(){

    }

    @CheckLogin
    fun sendCommend(){

    }

    private fun closeCommendList(){
        //执行从底部弹出动画
        val animIn = AnimationUtils.loadAnimation(this, R.anim.anim_out)
        animIn.duration = 500
        animIn.interpolator = AccelerateInterpolator()
        //设置动画监听
        animIn.setAnimationListener(object: Animation.AnimationListener{
            override fun onAnimationStart(animation: Animation?) {

            }

            override fun onAnimationEnd(animation: Animation?) {
                llCommentPanel?.visibility = View.GONE
                mRecyclerView.setIntercept(false)
            }

            override fun onAnimationRepeat(animation: Animation?) {

            }
        })
        //执行动画
        llCommentPanel.startAnimation(animIn)
    }

    private fun showCommendList(position: Int){
        var entity = videoList[position]
        val fragment = CommendDialogFragment(entity.item_id)
        fragment.show(supportFragmentManager, "videoCommend")
    }



    private fun showVideoCommendList(position: Int){
        mRecyclerView.setIntercept(true)
        var entity = videoList[position]
        //获取当前位置的评论列表UI组件
        llCommentPanel = (mRecyclerView.findViewHolderForLayoutPosition(position) as VideoPlayAdapter.VideoPlayViewHolder).dataBinding.llCommentPanel
        llCommentPanel.visibility = View.VISIBLE

        //初始化评论的RecyclerView
//        mRvCommends = (mRecyclerView.findViewHolderForLayoutPosition(position) as VideoPlayAdapter.VideoPlayViewHolder).dataBinding.rvComments
//        mRvCommends.layoutManager = LinearLayoutManager(this)
//        mCommendAdapter = VideoCommendAdapter(commendList)
//        mRvCommends.adapter = mCommendAdapter

        mRlvCommends = (mRecyclerView.findViewHolderForLayoutPosition(position) as VideoPlayAdapter.VideoPlayViewHolder).dataBinding.elvComments
        mExpandListCommendAdapter = CommendExpandListAdapter(commendList)
        mRlvCommends.setAdapter(mExpandListCommendAdapter)


        //执行从底部弹出动画
        val animIn = AnimationUtils.loadAnimation(this, R.anim.anim_in)
        animIn.duration = 500
        animIn.interpolator = AccelerateInterpolator()
        //设置动画监听
        animIn.setAnimationListener(object: Animation.AnimationListener{
            override fun onAnimationStart(animation: Animation?) {
               //加载当前视频的评论
                loadVideoCommendList(entity.item_id)
            }

            override fun onAnimationEnd(animation: Animation?) {

            }

            override fun onAnimationRepeat(animation: Animation?) {

            }
        })
        //执行动画
        llCommentPanel.startAnimation(animIn)
    }

    private fun loadVideoCommendList(itemId: String){
        lifecycleScope.launch {
            mViewModel.channel.send(VideoPlayViewIntent.LoadVideoCommends(0, itemId))
        }
    }

    override suspend fun sendViewIntent() {
        if(typeId == -1){ //加载推荐视频数据
            mViewModel.channel.send(VideoPlayViewIntent.LoadRecommendSimpleVideo(pageIndex, pageSize))
        }else{
            mViewModel.channel.send(VideoPlayViewIntent.LoadSimpleVideoByChannelId(channelId, pageIndex, pageSize))
        }
    }

    //下来刷新时，加载数据
    private fun loadVideoList(){
        lifecycleScope.launch {
            if(typeId == -1){ //加载推荐视频数据
                mViewModel.channel.send(VideoPlayViewIntent.LoadRecommendSimpleVideo(pageIndex, pageSize))
            }else{
                mViewModel.channel.send(VideoPlayViewIntent.LoadSimpleVideoByChannelId(channelId, pageIndex, pageSize))
            }
        }
    }

    override suspend fun collectUIState() {
        mViewModel.uiState.collect {
            when(it){
                is VideoPlayUiState.LoadSimpleVideoSuccess -> {
                    mDataBinding.smartRefresh.finishRefresh()
                    var oldListSize = videoList.size
                    //只有在下拉刷新时，且数据大于一条数据，才清理之前的数据，并整体刷新列表
                    if (pageIndex == 1 && oldListSize > 1) {
                        videoList.clear()
                        videoList.addAll(it.list)
                        mAdapter.notifyDataSetChanged() //整体刷新列表
                    } else {
                        videoList.addAll(it.list)
                        var startPosition =  if (oldListSize > 1) oldListSize - 1 else 1
                        mAdapter.notifyItemRangeChanged(startPosition, videoList.size - 1)  //指定范围，执行局部刷新
                    }

                    //自动播放第一条视频
                    if(pageIndex == 1){
                        mRecyclerView.postDelayed({
                            mVideoPlayer = (mRecyclerView.findViewHolderForLayoutPosition(0) as VideoPlayAdapter.VideoPlayViewHolder).dataBinding.gsyPlayer
                            if(mVideoPlayer != null){
                                mVideoPlayer?.isLooping = true
                                mVideoPlayer?.startPlayLogic()
                            }
                        }, 200)
                    }
                }
//                is VideoPlayUiState.LoadVideoCommendSuccess -> {
//                    if(it.list.isNotEmpty()){
//                       commendList.clear()
//                    }
//                    //添加点回复数据
//                    val locCommendSize = locReplayList.size
//                    it.list.forEachIndexed { index, commendEntity ->
//                        commendEntity.replytotal = 3
//                        //添加第一条
//                        val fromIndex1 = (locCommendSize - 2) % ((Math.random() * 10).toInt() + 1)
//                        commendEntity.replyList.addAll(locReplayList.subList(fromIndex1, fromIndex1 + 1))
//                        //添加第二条
//                        val fromIndex2 = (locCommendSize - 2) % ((Math.random() * 10).toInt() + 1)
//                        commendEntity.replyList.addAll(locReplayList.subList(fromIndex2, fromIndex2 + 1))
//                        //添加第三条
//                        val fromIndex3 = (locCommendSize - 2) % ((Math.random() * 10).toInt() + 1)
//                        commendEntity.replyList.addAll(locReplayList.subList(fromIndex3, fromIndex3 + 1))
//                    }
//
//                    commendList.addAll(it.list)
////                    mCommendAdapter.notifyDataSetChanged()
////                    mExpandListCommendAdapter.notifyDataSetChanged()
//                }
//                is VideoPlayUiState.LoadSimpleVideoFail -> {
//                    ToastUtils.showLong(it.msg)
//                }
//                is VideoPlayUiState.LoadVideoCommendFail -> {
//                    ToastUtils.showLong(it.msg)
//                }
                else -> {}
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if(mVideoPlayer != null){
            mVideoPlayer?.onVideoResume()
        }
    }

    override fun onPause() {
        super.onPause()
        if(mVideoPlayer != null){
            mVideoPlayer?.onVideoPause()
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        if(mVideoPlayer != null){
            mVideoPlayer?.release()
            mVideoPlayer = null
        }
    }

}